<template>
  <BasicModal centered
              v-bind="$attrs"
              :title="getTitle"
              :width="810"
              :bodyStyle="{overflowY:'hidden'}"
              :canFullscreen="false"
              :destroyOnClose="true"
              :maskClosable="false"
              @register="registerModal"
              @ok="handleSubmit"
  >
    <a-row type="flex" :gutter="5" style="margin: 0; padding: 0">
      <a-col flex="31.5%" style="border: 1px #ddd solid; padding-top: 5px">
        <CustomerTree @onClick="onClick"/>
      </a-col>
      <a-col flex="67%" style="border: 1px #ddd solid; padding-top: 10px; margin-left: 5px">
        <a-form ref="registerForm" :model="model" :rules="validatorRules" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
          <a-form-item name="customerDwmc" label="订购单位" :wrapperCol="{ span: 22 }">
            <a-form-item-rest>
            <a-input type="hidden" v-model:value="model.id"/>
            <a-input type="hidden" v-model:value="model.parentId"/>
            <a-input type="hidden" id="businessCustomer_ygsFmt" v-model:value="model.ygsFmt"/>
            <a-input type="hidden" v-model:value="model.customerId"/>
            <a-input type="hidden" v-model:value="model.orderId"/>
            <a-input type="hidden" v-model:value="model.businessId"/>
            <a-input type="hidden" v-model:value="model.scheduleId"/>
            </a-form-item-rest>
            <a-input v-model:value="model.customerDwmc" readonly style="width: calc(100% - 20px)"></a-input>
          </a-form-item>
          <a-form-item name="adultNo" label="人数">
            <a-form-item-rest>
            成人数
            <a-input type="text" v-model:value="model.adultNo" @blur="fsmony" style="width: 80px" autocomplete="off"/>
            ， 儿童数
            <a-input type="text" v-model:value="model.childNo" @blur="fsmony" style="width: 80px" autocomplete="off"/>
            ， 陪同数
            <a-input type="text" v-model:value="model.escortNo" @blur="fsmony" style="width: 80px" autocomplete="off"/>
            </a-form-item-rest>
          </a-form-item>
          <a-form-item label="价格">
            <a-form-item-rest>
            成人价
            <a-input type="text" id="businessCustomerCrj" aria-valuemax="10" v-model:value="model.crj" @blur="fsmony" style="width: 80px" autocomplete="off"/>
            ，
            儿童价
            <a-input type="text" id="businessCustomerEtj" aria-valuemax="10"
                    datatype="/^-?[1-9]+(\.\d+)?$|^-?0(\.\d+)?$|^-?[1-9]+[0-9]*(\.\d+)?$/" nullmsg="不能为空"
                    errormsg="必须为数字，可以有小数" v-model:value="model.etj" @blur="fsmony" style="width: 80px" autocomplete="off"/>
            ，
            陪同价
            <a-input type="text" id="businessCustomerPtj" aria-valuemax="10"
                    datatype="/^-?[1-9]+(\.\d+)?$|^-?0(\.\d+)?$|^-?[1-9]+[0-9]*(\.\d+)?$/" nullmsg="不能为空"
                    errormsg="必须为数字，可以有小数" v-model:value="model.ptj" @blur="fsmony" style="width: 80px" autocomplete="off"/>
            </a-form-item-rest>
          </a-form-item>
          <a-form-item label="优惠"><!-- v-if="model.orderSn"-->
            <a-form-item-rest>
            同行返
            <a-input type="text" id="businessCustomerCrj" aria-valuemax="10" v-model:value="model.priceRoom" @blur="fsmony" style="width: 80px" autocomplete="off"/>
            ，
            会员返
            <a-input type="text" id="businessCustomerCrj" aria-valuemax="10" v-model:value="model.priceVip" @blur="fsmony" style="width: 80px" autocomplete="off"/>
            ，
            小计
            <a-input type="text" id="businessCustomerCrj" aria-valuemax="10" v-model:value="model.priceTol" @blur="fsmony" style="width: 93px" autocomplete="off"/>
            </a-form-item-rest>
          </a-form-item>
          <a-form-item label="增项">
            <a-form-item-rest>
            金额
            <a-input type="text" v-model:value="model.addPrice" @blur="fsmony" style="width: 94px" autocomplete="off"/>
            ， 说明
            <a-input type="text" v-model:value="model.addMark" style="width: 242px" autocomplete="off"/>
            </a-form-item-rest>
          </a-form-item>
          <a-form-item label="减项">
            <a-form-item-rest>
            金额
            <a-input type="text" v-model:value="model.subPrice" @blur="fsmony" style="width: 94px" autocomplete="off"/>
            ， 说明
            <a-input type="text" v-model:value="model.subMark" style="width: 242px" autocomplete="off"/>
            </a-form-item-rest>
          </a-form-item>
          <a-form-item name="ygs" label="应收">
            <a-form-item-rest>
            <a-input type="text" id="businessCustomerYgs" aria-valuemax="20" class="formText" v-model:value="model.ygs" style="width: 125px" autocomplete="off"/>
            <span v-if="model.scheduleId">
            ， 余位
            <label class="text-blue-500">{{ residue.resi }}/{{ residue.seat == 0 ? '现询' : residue.seat}}</label>
            </span>
            </a-form-item-rest>
          </a-form-item>
          <a-form-item name="jzsj" label="收客人" >
            <a-form-item-rest>
            <JDictSelectTag v-model:value="model.skrId" dictCode="sys_user,realname,id@departSales" :showSearch="true" authFilter="authUser" :styler="{width: '125px'}"/>
            ，收客时间
            <a-date-picker v-model:value="model.sksj" valueFormat="YYYY-MM-DD" style="width: 125px"/>
            </a-form-item-rest>
          </a-form-item>
          <a-form-item label="备注" :wrapperCol="{ span: 19 }">
            <a-textarea v-model:value="model.bz" :rows="4" :cols="6" class="textarea"/>
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>

  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, reactive, unref, computed, onMounted } from "vue";
import { BasicModal, useModalInner } from "/@/components/Modal";
import { businessCustomerById, businessCustomerSave } from "./business.api";
import { modify } from "/@/views/shop/orders/orders.api";
import { ValidateErrorEntity } from "ant-design-vue/es/form/interface";
import { useUserStore } from "/@/store/modules/user";
import { useMessage } from "/@/hooks/web/useMessage";
import JDictSelectTag from "/@/components/Form/src/jeecg/components/JDictSelectTag.vue";
import CustomerTree from "/@/views/full/customer/components/CustomerTree.vue";
import moment from 'dayjs'

const { createMessage: $message } = useMessage();
const emit = defineEmits(["success", "register"]);
const isUpdate = ref(true);
const rowId = ref('');
const registerForm = ref();
let residue = reactive<any>({});
let model   = reactive<any>({});

const validatorRules = {
  customerDwmc: [{ required: true, message: "请选择采购单位!" }],
  ygs: [
    { required: true, message: "不能为空!" },
    { pattern:/^-?[1-9]+(\.\d+)?$|^-?0(\.\d+)?$|^-?[1-9]+[0-9]*(\.\d+)?$/, message: '输入的金额格式有误' },
  ], //, trigger: 'blur'
  adultNo: [
    { required: true, message: "不能为空!" },
    { pattern:/^-?[1-9]+(\.\d+)?$|^-?0(\.\d+)?$|^-?[1-9]+[0-9]*(\.\d+)?$/, message: '输入的金额格式有误' },
  ]
};

//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  resetFields();
  model.orderId = data?.params.orderId
  model.businessId = data?.params.businessId
  model.skrId = useUserStore().getUserInfo?.id;

  model.scheduleId = '';
  model.crj = 0;
  model.etj = 0;
  model.priceVip = 0;
  model.priceRoom = 0

  if (unref(isUpdate)) {
    businessCustomerById({ id: data.params.id,  }).then((res) => {
      Object.assign(model, res.result);
      let vip = model.priceVip || 0 ;
      let roo = model.priceRoom|| 0;
      model.priceTol =  (Number(vip) + Number(roo)) * (Number(model.adultNo) + Number(model.childNo));
    })
  } else if (data.params.scheduleId) {
    model.scheduleId = data.params.scheduleId;
    model.crj = data.params.crj;
    model.etj = data.params.etj;
    model.priceVip  = data.params.priceVip;
    model.priceRoom = data.params.priceRoom;
    // 余位
    residue = {
      sumPersonNo: data.params.sumPersonNo,
      seat: data.params.seat,
      resi: data.params.resi, 
    }
  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '采购单位 - 新增' : '采购单位 - 编辑'));

//表单提交事件
async function handleSubmit() {
  
  //如果机位配置不是现询，才去检查库存量
  if (residue.seat > 0) {
    //当前出单人数
    var personNo  = Number(model.adultNo) + Number(model.childNo) + Number(model.escortNo);
    //检查库存， 余位量 = 配置量 - 出单量 - 当前量
    var seatCheck = Number(residue.resi || 0) - personNo;
    if ( seatCheck < 0 ) {
      $message.warning("库存不足，当前余位还有 " + residue.resi + " 个。")
      return false;
    }
  }

  await registerForm.value.validate().then(async () => {
    try {
      setModalProps({ confirmLoading: true });
      //重新构造表单提交对象,切记不可修改router对象，数组修改为字符串容易造成界面混乱
      let params = Object.assign({}, model);
      await businessCustomerSave( params ).then(() => {
        //更新产品订单
        handleProductOrderModify();
        closeModal();
        //刷新列表
        emit('success', model.businessId);
      })
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }).catch((error: ValidateErrorEntity<any>) => {
    console.log('error', error);
  });
}

//
async function handleProductOrderModify() {
  try {
    if (!model.orderSn) {
      return false;
    }
    let values = {
      orderSn: model.orderSn,
      goodsPrice: model.crj,
      num: model.adultNo,
      childPrice: model.etj,
      childNum: model.childNo,
      addPrice: model.addPrice,
      addMark: model.addMark,
      subPrice: model.subPrice,
      subMark: model.subMark,
      priceVip: model.priceVip,
      priceRoom: model.priceRoom
    }
    await modify(values.orderSn, values);
  } catch (e) {
    console.log(e);
  } 
}

//表单重置
function resetFields() {
  model.id = null;
  model.parentId     = '';
  model.customerId   = '';
  model.customerDwmc = '';
  model.adultNo  = 0;
  model.childNo  = 0;
  model.escortNo = 0;
  model.crj = 0;
  model.etj = 0;
  model.ptj = 0;
  model.ygs = 0;
  model.addPrice = 0;
  model.subPrice = 0;
  model.addMark  = '';
  model.subMark  = '';
  model.skrId = '';
  model.sksj  = moment().format('YYYY-MM-DD');
  model.bz    = '';
  model.orderId    = '';
  model.businessId = '';
  model.orderSn    = '';
  model.priceTol   = '';
}

//应收金额计算
function fsmony() {
  var etj = 0, crj = 0, ptj = 0, ygs = 0;
  var adultNo = 0, childNo = 0, escortNo = 0;
  var vip = 0, roo= 0, add = 0, sub = 0;
  //单价
  etj = model.etj = getValue(model.etj)
  crj = model.crj = getValue(model.crj)
  ptj = model.ptj = getValue(model.ptj)
  //人数
  adultNo  = model.adultNo  = getValue(model.adultNo);
  childNo  = model.childNo  = getValue(model.childNo); 
  escortNo = model.escortNo = getValue(model.escortNo);

  if (residue.seat > 0) {
    //当前出单人数
    var personNo  = Number(model.adultNo) + Number(model.childNo) + Number(model.escortNo);
    //检查库存， 余位量 = 配置量 - 出单量 - 当前量
    var seatCheck = Number(residue.resi || 0) - personNo;
    if ( seatCheck < 0 ) {
      $message.warning("库存不足，当前余位还有 " + residue.resi + " 个。")
      return false;
    }
  }

  //团款
  ygs = adultNo * crj;
  ygs = ygs + childNo * etj;
  ygs = ygs + escortNo * ptj;

  //优惠
  vip = model.priceVip  = getValue(model.priceVip);
  roo = model.priceRoom = getValue(model.priceRoom);
  model.priceTol = (Number(vip) + Number(roo)) * (Number(adultNo) + Number(childNo));
  ygs = ygs - model.priceTol;

  //console.info(ygs, model.priceVip, roo, adultNo, childNo);
  //增项
  add = model.addPrice = getValue(model.addPrice);
  sub = model.subPrice = getValue(model.subPrice);

  ygs = ygs + Number(add) - Number(sub);

  if (isNaN(parseFloat(ygs))) {
    $message.warning("输入的金额格式有误")
    return false;
  }

  model.ygs = ygs;

  function getValue(v) {
    return (v ? v : 0)
  }
}


//-----------------------------ztree---------------------------------------------
/**
 * 树节点点击事件
 * 当点城市 type = 0, 加1后 customer.type = 1 公司
 * @param e
 * @param treeId
 * @param treeNode
 * @returns {boolean}
 */
function onClick(treeNode) {
  if (treeNode.type == 2) {
    model.customerId = treeNode.id
    model.parentId = treeNode.pId
    model.customerDwmc = treeNode.pathName
  }
  //console.info("onClick", treeNode);
}
</script>
